#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <assert.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/sem.h>
#include <errno.h>
#define IPCKEY 0x100

void* create_shm_buf(void);
int create_sem(void);

#include "pv.c"

int main()
{
    unsigned char* shm_buf = create_shm_buf();
    int sem = create_sem();
    int i;
    for(i=0; ; i++)
    {
        printf("wait <%d>0.\n",i);
        semwait(sem);
        printf("wait <%d>1.\n",i);

        *(int*)(shm_buf)    = i;
        *(int*)(shm_buf+4)  = i;

        sleep(1);

        printf("post <%d>0.\n",i);
        sempost(sem);
        printf("post <%d>0.\n",i);

        if(i>=1024*1024)
            i = 0;
    }
    return 0;
};


void* create_shm_buf(void)
{
    void* buf;

    #define SHM_SIZE    102400
    int shm_id = shmget(IPCKEY, SHM_SIZE, 0640|IPC_CREAT|IPC_EXCL);
    assert(shm_id != -1);

    buf = shmat(shm_id, NULL, 0);
    printf("======%s OK.\n", __FUNCTION__);

    return buf;
}


union semun
{
    int val;
    struct semid_ds* buf;
    unsigned short* array;
}arg;


int create_sem(void)
{
    key_t key;
    key = ftok("/", 0);

    int sem_id;
    sem_id = semget(key, 1, IPC_CREAT | 0666);
    printf("errno = %d.\n", errno);
    assert(-1 != sem_id);

    union semun sem;
    sem.val = 1;
    semctl(sem_id, 0, SETVAL, sem);

    printf("======%s OK.\n", __FUNCTION__);

    return sem_id;
}
